package com.tim.app.ui.activity.found;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.design.widget.AppBarLayout;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.application.library.log.DLOG;
import com.application.library.net.StringResponseCallback;
import com.application.library.widget.roundimg.RoundedImageView;
import com.application.library.widget.smarttab.SmartTabLayout;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.lzy.okhttputils.OkHttpUtils;
import com.tim.app.R;
import com.tim.app.constant.AppKey;
import com.tim.app.server.api.API_Discover;
import com.tim.app.server.entry.MusicAlbum;
import com.tim.app.server.logic.UserManager;
import com.tim.app.server.net.ServerAddressManager;
import com.tim.app.server.result.MusicAlbumDetailResult;
import com.tim.app.server.result.ResponseResult;
import com.tim.app.share.CustomShareBoard;
import com.tim.app.ui.activity.BaseActivity;
import com.tim.app.ui.activity.MainActivity;
import com.tim.app.ui.activity.record.RecordActivity;
import com.tim.app.ui.adapter.TabAdapter;
import com.tim.app.ui.fragment.found.MusicAlbumProgramFragment;
import com.tim.app.ui.fragment.found.MusicDetailInfoFragment;
import com.tim.app.util.SoftKeyboardUtil;

import jp.wasabeef.glide.transformations.BlurTransformation;


/**
 * 专辑详情页
 */
public class MusicAlbumDetailActivity extends BaseActivity {

    public static final String TAG = "MusicAlbumDetailActivity";

    private AppBarLayout appbar;
    private ImageView ivBack, ivReport;
    private TextView tvTitle;
    private View vLine;

    private TextView tvMusicAlbumTitle;
    private ImageView ivBg;
    private RoundedImageView rivImage;
    private TextView tvPlayCount;

    private ViewPager vpMusicAlbum;
    private TabAdapter pageAdapter;
    private SmartTabLayout tab_layout;
    private boolean isFromPush = false;

    MusicDetailInfoFragment musicDetailInfoFragment;
    MusicAlbumProgramFragment musicAlbumProgramFragment;

    private View rlGotoRecord;

    private MusicAlbum data;

    public static void start(Context context, MusicAlbum musicAlbum, boolean isFromPush) {
        Intent intent = new Intent(context, MusicAlbumDetailActivity.class);
        intent.putExtra(AppKey.IS_FROM_PUSH, isFromPush);
        intent.putExtra("data", musicAlbum);
        if (isFromPush) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_music_album_detail;
    }


    @Override
    public void initView() {
        appbar = (AppBarLayout) findViewById(R.id.appbar);
        ivBack = (ImageView) findViewById(R.id.ivBack);
        ivReport = (ImageView) findViewById(R.id.ivReport);
        tvTitle = (TextView) findViewById(R.id.tvTitle);

        tvMusicAlbumTitle = (TextView) findViewById(R.id.tvMusicAlbumTitle);
        ivBg = (ImageView) findViewById(R.id.ivBg);

        rivImage = (RoundedImageView) findViewById(R.id.rivImage);
        tvPlayCount = (TextView) findViewById(R.id.tvPlayCount);
        vLine = findViewById(R.id.vLine);

        tab_layout = (SmartTabLayout) findViewById(R.id.tab_layout);
        vpMusicAlbum = (ViewPager) findViewById(R.id.vpMusicAlbum);

        rlGotoRecord = findViewById(R.id.rlGotoRecord);

        ivBack.setOnClickListener(this);
        ivReport.setOnClickListener(this);
        rlGotoRecord.setOnClickListener(this);

        data = (MusicAlbum) getIntent().getSerializableExtra("data");
        isFromPush = getIntent().getBooleanExtra(AppKey.IS_FROM_PUSH, false);

        musicDetailInfoFragment = MusicDetailInfoFragment.newInstance(data);
        musicAlbumProgramFragment = MusicAlbumProgramFragment.newInstance(data);
        pageAdapter = new TabAdapter(getSupportFragmentManager());
        pageAdapter.addFragment(musicDetailInfoFragment, getString(R.string.musicAlbumDetail));
        pageAdapter.addFragment(musicAlbumProgramFragment, getString(R.string.musicAlbumProgram));
        vpMusicAlbum.setOffscreenPageLimit(2);
        vpMusicAlbum.setAdapter(pageAdapter);
        vpMusicAlbum.setCurrentItem(1);
        tab_layout.setViewPager(vpMusicAlbum);

        appbar.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {

            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                if (verticalOffset == 0) {  //展开状态
                    ivBack.setImageResource(R.drawable.ic_back_white);
                    ivReport.setImageResource(R.drawable.ic_more_white);
                    tvTitle.setVisibility(View.GONE);
                } else if (Math.abs(verticalOffset) >= appBarLayout.getTotalScrollRange()) {
                    vLine.setVisibility(View.VISIBLE);
                    ivBack.setImageResource(R.drawable.ic_back_black);
                    ivReport.setImageResource(R.drawable.ic_more);
                    tvTitle.setVisibility(View.VISIBLE);
                } else {//中间状态
                    vLine.setVisibility(View.GONE);
                    tvTitle.setVisibility(View.GONE);
                }

                int maxScroll = appBarLayout.getTotalScrollRange();
                float percentage = (float) Math.abs(verticalOffset) / (float) maxScroll;
                if (percentage > 0.7f) {
                    tvTitle.setVisibility(View.VISIBLE);
                    ivBack.setImageResource(R.drawable.ic_back_black);
                } else {
                    tvTitle.setVisibility(View.GONE);
                    ivBack.setImageResource(R.drawable.ic_back_white);
                }
            }
        });
        refreshUi(data);

    }


    @Override
    public void initData() {
        if (null != data && !TextUtils.isEmpty(data.getId()
        )) {
            API_Discover.ins().getMusicAlbumDetailData(TAG, data.getId(), detailCallback);
        }
    }


    StringResponseCallback detailCallback = new StringResponseCallback() {
        @Override
        public boolean onStringResponse(String resultValue, int errcode, String errMsg, int id, boolean fromcache) {
            if (errcode == ResponseResult.ResultStatus.OK && resultValue != null) {
                MusicAlbumDetailResult result = new Gson().fromJson(resultValue, MusicAlbumDetailResult.class);

                if (null != result && null != result.getRes() && null != result.getRes().getAlbum()) {
                    if (null != result.getRes().getAlbum()) {
                        data = result.getRes().getAlbum();
                        refreshUi(data);
                        musicDetailInfoFragment.updateData(data);
                        musicAlbumProgramFragment.updateData(data);
                    }
                }

            } else {
                DLOG.e(TAG, errMsg);
//                ToastUtil.showToast(errMsg);
            }
            return false;
        }
    };


    private void refreshUi(MusicAlbum data) {
        if (null != data) {
            if (!TextUtils.isEmpty(data.getName())) {
                tvMusicAlbumTitle.setText(data.getName());
                tvTitle.setText(data.getName());
            }
            if (data.getIsOffice() == 1) {
                rlGotoRecord.setVisibility(View.VISIBLE);
            } else {
                rlGotoRecord.setVisibility(View.GONE);
            }
            tvPlayCount.setText(getString(R.string.playCount, String.valueOf(data.getPlayCount())));
            Glide.with(this)
                    .load(data.getImage()).error(new ColorDrawable(Color.parseColor("#eeeeee"))).into(rivImage);
            Glide.with(this)
                    .load(data.getImage()).error(new ColorDrawable(Color.parseColor("#eeeeee")))
                    .bitmapTransform(new BlurTransformation(this, AppKey.DETIAL_RADIUS))//高斯模糊
                    .into(ivBg);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }


    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkHttpUtils.getInstance().cancelTag(TAG);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (isFromPush) {
            Intent intent = new Intent(this, MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ivBack://返回
                finish();
                break;
            case R.id.ivReport:
                CustomShareBoard shareBoard = new CustomShareBoard(this, CustomShareBoard.ShareFrom.NORMAL);
                String targetUrl = data.getShareUrl();
                String sinaDesc = "我正在茉莉社区收听\"" + data.getName() + "\"，听听别人的情感经历，就能赚零花钱，还可以微信提现！推荐你试试~ " + targetUrl;
                String imageUrl = ServerAddressManager.SHARE_DEFAULT_LOGO_URL;
                if (null != data.getImage()) {
                    imageUrl = data.getImage();
                }
                String desc = "";
                desc = "在茉莉社区听听别人情感经历，就能赚零花钱，还可以微信提现！";
                shareBoard.setShareInfo("我正在收听\"" + data.getName() + "\"", desc, sinaDesc, imageUrl, imageUrl, targetUrl);
                shareBoard.showPopup(false);
                break;
            case R.id.rlGotoRecord:
                RecordActivity.start(this, data.getId());
                break;
        }
    }

}
